#!/bin/bash

sources_dir=~/bettereye/trunk/
test_name=${2}
module_name=`echo ${test_name} | egrep -o '^\w+_' | tr -d _`
test_file_name="${sources_dir}/${module_name}/${module_name}_tests.plg"

test_content=`egrep -r --exclude-dir="*svn*" -A 3 -h ${test_name} ${test_file_name}`
test_rule=`echo "${test_content}" | head -n 2 | tail -n 1`
test_input=`echo "${test_content}" | head -n 3 | tail -n 1`
test_result=`echo "${test_content}" | head -n 4 | tail -n 1`

(
cat <<very-end
main :-

   consult('./utils/os_helpers.plg'),
   get_environment(Lib_path),
   concat_atom([Lib_path, 'lists.pl'], Lib_lists),

   use_module(Lib_lists),

   consult('./utils/ebnf_helpers.plg'),
   consult('./utils/file_to_charLst.plg'),
   consult('./utils/test_helpers.plg'),
   consult('./utils/syntax_helpers.plg'),
   consult('./utils/simplifier.plg'),
   consult('./utils/pretty_print.plg'),

   consult('./a2/a2_gramma.plg'),
   consult('./a3/a3_gramma.plg'),
   consult('./a4/a4_gramma.plg'),
   consult('./a5/a5_gramma.plg'),
   consult('./a6/a6_gramma.plg'),
   consult('./a7/a7_gramma.plg'),
   consult('./a8/a8_gramma.plg'),
   consult('./a9/a9_gramma.plg'),
   consult('./a10/a10_gramma.plg'),
   consult('./a11/a11_gramma.plg'),
   consult('./a12/a12_gramma.plg'),
   consult('./a13/a13_gramma.plg'),

   test4(${test_name}, ${test_rule} ${test_input} X), writeq(X),
   halt.
very-end
) > tmp.plg

new_result=`swipl -q -s tmp.plg -g main`

echo "${test_result}" > /tmp/1.plg
echo "${new_result}" > /tmp/2.plg

cp "${test_file_name}" "${test_file_name}.bak"

case ${1} in
   "-s" ) vim -d /tmp/1.plg /tmp/2.plg;;
   #"-a" ) sed -n "s/${test_result}/${new_result}/p" ${test_file_name};;
   "-a" ) 
         line_num=`grep -F -n "${test_result}" ${test_file_name} | egrep -o "^\w+: " | tr -d :`
         sed -ri "${line_num}s/.*/\t\t\t${new_result}/" ${test_file_name}
         ;;
esac
